package com.fly.office.controller;

import com.alibaba.excel.ExcelWriter;
import com.fly.office.controller.model.Data1;
import com.fly.office.controller.model.User;
import com.fly.office.excel.ExcelHandler;
import com.fly.office.excel.ExcelTplHandler;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.ByteArrayOutputStream;
import java.util.*;

@RestController
public class ExcelController {

    @GetMapping("export")
    public void export(HttpServletResponse response)
    {
        int num = 0;
        ExcelHandler handler = null;
        ExcelWriter excelWriter = null;
        try {
            String fileName = "测试.xlsx";
            ServletOutputStream bos1;
            ByteArrayOutputStream bos = new ByteArrayOutputStream();
            //创建handler对象
            handler = new ExcelHandler();
            excelWriter = handler.create(bos, Data1.class);

            List<Data1> list = new ArrayList<>(1024);

            for (int i = 0; i < 1000000; i++) {//总数据 100W条
                num++;
                list.add(new Data1("张三" + num, "123abc" + num));
            }
            handler.write(excelWriter, list);
            handler.finish(excelWriter);
            String codedFilename = "attachment; filename=" + java.net.URLEncoder.encode(fileName, "UTF-8");
            response.setHeader("Content-Disposition", codedFilename);
            bos1 = response.getOutputStream();
            bos1.write(bos.toByteArray());
        } catch (Exception ex) {
            ex.printStackTrace();
        }
    }


    @GetMapping("tpl/export")
    public void tplExport(HttpServletResponse response)
    {
        //模板
        String template = ExcelTplHandler.convertTemplatePath("excel/data_list.xlsx");
        //基础数据
        Map<String, Object> map = new HashMap<>();
        map.put("person", "fly");
        map.put("now", "2021-07-19");
        //列表数据
        List<User> list = new ArrayList<>();

        Random random = new Random();
        int age;
        User user=null;
        for(int i=0;i<1000;i++)
        {
            age = random.nextInt(99);
            user=new User();
            user.setName("张三"+i);
            user.setAge(age);
            user.setCreateTime("2021-07-20");
            list.add(user);
        }
        map.put("maplist", list);
        String fileName="报表测试.xlsx";
        ExcelTplHandler.export(template,map,list,fileName,response);
    }

}
